import platform from '../../config/platform';
import BaseMall, { IQueryDetailParams, IQueryListParams } from './BaseMall';
import { GoodsDetail } from './typing/Mall';
import md5 = require('md5');
import dayjs = require('dayjs');
import SNApi from '../../api/SN';

export default class SNMall extends BaseMall {
  private appKey = platform.sn.appKey;
  private appSecret = platform.sn.appSecret;

  queryList(params: IQueryListParams<any>): Promise<GoodsDetail[]> {
    const appMethod = 'suning.netalliance.searchcommodity.query';
    const commonParams = this.genCommonParams();
    const businessParams = {
      sn_request: {
        sn_body: {
          querySearchcommodity: {
            keyword: params.searchContent,
            pageIndex: params.page,
            size: params.pageSize,
          },
        },
      },
    };
    const signInfo = this.genSignature(appMethod, commonParams, businessParams);
    const headers = {
      ...commonParams,
      appMethod,
      signInfo,
    };

    return SNApi.getInstance().search(headers, businessParams as any) as any;
  }
  queryDetail(params: IQueryDetailParams): Promise<GoodsDetail> {
    void params;
    throw new Error('Method not implemented.');
  }

  private genCommonParams() {
    return {
      appRequestTime: dayjs().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss'),
      format: 'json',
      appKey: this.appKey,
      versionNo: 'v1.2',
    } as const;
  }

  private genSignature(appMethod, commonParams, businessParams) {
    const businessParamsBase64 = Buffer.from(JSON.stringify(businessParams)).toString('base64');
    const { appRequestTime, appKey, versionNo } = commonParams;
    const signStr = `${this.appSecret}${appMethod}${appRequestTime}${appKey}${versionNo}${businessParamsBase64}`;

    return md5(signStr);
  }
}
